package com.xwm93up.threadsecurity;

/**
 * @Description: desc
 * @Author: xwm93up
 * @Since: 2022/5/20 14:40
 */
public class ThreadDemo {
    static final Object obj = new Object();

    // 第一个子线程
    static class ThreadA implements Runnable{

        @Override
        public void run() {
            int count = 10;

            while (count > 0) {
                synchronized (ThreadDemo.obj){
                    System.out.println(Thread.currentThread().getName() + "-----------" + count);
                    count--;

                    synchronized (ThreadDemo.obj) {
                        // notify()方法会唤醒因为对象的wait()而处于等待状态的线程, 从而使得该线程有机会获得对象锁.
                        // 调用notify()后, 当前线程并不会立即释放锁, 而是继续执行当前代码, 直到synchronized中的代码全部执行完毕.
                        ThreadDemo.obj.notify();

                        try {
                            ThreadDemo.obj.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }

            }
        }
    }

    // 第一个子线程
    static class ThreadB implements Runnable{

        @Override
        public void run() {
            int count = 10;

            while (count > 0) {
                synchronized (ThreadDemo.obj){
                    System.out.println(Thread.currentThread().getName() + "-----------"  + count);
                    count--;

                    synchronized (ThreadDemo.obj) {
                        // notify()方法会唤醒因为对象的wait()而处于等待状态的线程, 从而使得该线程有机会获得对象锁.
                        // 调用notify()后, 当前线程并不会立即释放锁, 而是继续执行当前代码, 直到synchronized中的代码全部执行完毕.
                        ThreadDemo.obj.notify();

                        try {
                            ThreadDemo.obj.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }

            }
        }
    }

    public static void main(String[] args) {
        new Thread(new ThreadA(), "A的线程1").start();
        new Thread(new ThreadB(), "B的线程1").start();
    }
}
